<template>
  <el-dialog style="top: 10%" v-model="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()" label-width="120px">
      <el-row>
        <el-col :span="12">
          <el-form-item prop="status" label="状态">
            <el-tag v-if="dataForm.status == 9" type="danger">未处理</el-tag>
            <el-tag v-else-if="dataForm.status == -1" type="danger">无效</el-tag>
            <el-tag v-else type="success">已处理</el-tag>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="posi" label="手机号">
            {{ hidePhoneMiddle(dataForm.phone) }}
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item prop="name" label="姓名">
            <el-input v-model="dataForm.name" placeholder="请输入姓名"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="posi" label="职位">
            <el-input v-model="dataForm.posi" placeholder="请输入职位"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item prop="email" label="邮箱">
            <el-input v-model="dataForm.email" placeholder="请输入邮箱"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="email" label="采购意向">
            <el-input v-model="dataForm.prod" placeholder="请输入采购意向"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item prop="email" label="地址">
            <el-input v-model="dataForm.area" placeholder="请输入地址"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12"> </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item prop="company" label="公司名称">
            <div style="display: flex">
              <el-select ref="companySelectRef" v-model="dataForm.company" placeholder="请输入公司名称查询" clearable filterable allow-create style="flex: 1 1 auto">
                <el-option v-for="item in companyOptions" :key="item.name" :label="item.name" :value="item.name"></el-option>
              </el-select>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-button type="primary" @click="handleQueryCompany" style="margin-left: 8px; white-space: nowrap">查询</el-button>
        </el-col>
      </el-row>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="danger" @click="cancle()">数据无效，下一条</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">保存,退出</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle(1)">保存,下一条</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { nextTick, reactive, ref } from "vue";
import baseService from "@/service/baseService";
import { IObject } from "@/types/interface";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
import { debounce } from "lodash-es";
const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);
import { ElMessageBox } from "element-plus";
const visible = ref(false);
const dataFormRef = ref();
const companyLoading = ref(false);
const companyOptions = ref<IObject[]>([]);
import { useRoute, useRouter } from "vue-router";
// 在 <script setup> 中追加
interface QueryParams {
  cid?: string;
  keyword?: string;
  cStatus?: string;
  cUpdaterName?: string;
  cProd?: string;
}
let queryCache = reactive<QueryParams>({}); // 用来保存父页面传过来的筛选条件

const router = useRouter();
const route = useRoute();
const dataForm = reactive({
  id: "" as any,
  company: "", //公司
  name: "", //姓名
  phone: "", //联系电话
  email: "", //邮箱
  posi: "", //职位
  status: "", //状态
  area: "",
  prod: ""
});

// 用于快速验证的有效公司集合
const validCompanies = ref(new Set<string>());
const companySelectRef = ref();

const rules = ref({});

const init = (roleId?: number, query?: QueryParams) => {
  visible.value = true;
  dataForm.id = roleId;
  // 缓存查询条件
  Object.assign(queryCache, query || {});
  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  nextTick(() => {
    getInfo(roleId);
    companyOptions.value = [];
  });
};

// 获取信息
const getInfo = (id?: number) => {
  if (!id) {
    return;
  }
  baseService.get(`/noc/companybasicinfotmp/info/${id}`).then((res) => {
    Object.assign(dataForm, res.data);
  });
};

const cancle = () => {
  ElMessageBox.confirm("确定要将选中的记录标记为无效吗?", "提示", {
    confirmButtonText: t("confirm"),
    cancelButtonText: t("cancel"),
    type: "warning"
  })
    .then(() => {
      dataForm.status = "-1";
      dataFormSubmitHandle(1);
      ElMessage.success("操作成功");
      router.push(0).then(() => {
        router.go(0); // 导航完成后刷新页面
      });
    })
    .catch(() => {
      // 取消操作
    });
};

// 表单提交
const dataFormSubmitHandle = (type?: number) => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid && dataForm.status != "-1") {
      return false;
    }
    // 验证公司是否在有效集合中
    if ((!dataForm.company || !validCompanies.value.has(dataForm.company)) && dataForm.status != "-1") {
      ElMessage.error("请从查询结果中选择有效的公司");
      return;
    }
    // 合并额外参数
    const payload = {
      ...dataForm,
      ...queryCache // 这里一次性把 cid、keyword、cStatus、cUpdaterName、cProd 带过去
    };
    (dataForm.id ? baseService.post("/noc/companybasicinfotmp/update", payload) : baseService.post("/noc/companybasicinfotmp/save", payload)).then((res) => {
      if (res.code === 0) {
        ElMessage.success("保存成功");
      }
      //刷新数据父页面数据
      emit("refreshDataList");
      if (type == 1) {
        getInfo(res.data.id);
      } else {
        ElMessage.success({
          message: t("prompt.success"),
          duration: 500,
          onClose: () => {
            visible.value = false;
            emit("refreshDataList");
          }
        });
      }
    });
  });
};

// 公司名称输入处理
const handleCompanyInput = debounce(async (query: string) => {
  if (query && query.length >= 2) {
    // 至少2个字符才查询
    await queryCompany(query);
  } else {
    companyOptions.value = [];
    validCompanies.value.clear();
  }
}, 500);

// 查询公司列表
const queryCompany = async (query: string) => {
  companyLoading.value = true;
  try {
    const res = await baseService.get("/noc/companybasicinfotmp/search", {
      company: query
    });
    companyOptions.value = res.data.list || [];
    // 更新有效公司集合
    if (res.data.list) {
      const names = res.data.list.map((item: any) => item.name);
      validCompanies.value = new Set(names);

      // ✅ 关键：强制打开下拉框
      nextTick(() => {
        companySelectRef.value?.focus();
        companySelectRef.value?.blur();
      });
    } else {
      ElMessage.error("未查询到相关公司");
    }
  } catch (error) {
    ElMessage.error("查询公司列表失败");
    companyOptions.value = [];
    validCompanies.value.clear();
  } finally {
    companyLoading.value = false;
  }
};

// 手动查询公司
const handleQueryCompany = async () => {
  if (!dataForm.company) {
    ElMessage.warning("请输入公司名称");
    return;
  }
  await queryCompany(dataForm.company);
};

// 公司选择处理
const handleCompanySelect = (company: IObject) => {
  // 这里可以添加选中公司后的其他处理逻辑
  // 例如自动填充相关信息
  companyOptions.value = []; // 选择后清空查询结果
};

// 最简单的隐藏手机号中间4位方法
const hidePhoneMiddle = (phone: string) => {
  if (!phone) return "";
  if (phone.length < 7) return phone; // 太短的号码不处理

  // 替换中间4位为*号
  return phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
};

defineExpose({
  init
});
</script>
